package com.call.project;

import com.call.project.frame.SettingFrame;
import com.call.project.frame.TrayManager;
import com.call.project.frame.WelcomeWindow;
import com.call.project.jni.CInterface;
import com.call.project.utils.ConfigUtils;
import com.call.project.utils.OSinfo;
import com.call.project.web.MySpringApplication;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;

/**
 * Created by IntelliJ IDEA.
 * User: wk
 * Date: 2017-03-06 上午10:28
 */
public class CallApplication {
    private static String              commonArgs[];
    private static MySpringApplication mySpringApplication = new MySpringApplication();
    private static final Logger        logger              = LoggerFactory.getLogger(CallApplication.class);
    public static final String APP="app.exe";
    private static final String MAIN="会议呼叫系统.exe";
    public static java.util.List<String> getPID(String name) {
        java.util.List<String> pidList = new ArrayList<>();
        String pid = null;
        String cmd = "tasklist /nh /FI \"IMAGENAME eq "+name+"\"";
        try {
            Runtime runtime = Runtime.getRuntime();
            Process process = runtime.exec(cmd);
            BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String line = null;
            while ((line = br.readLine()) != null) {
                if (line.indexOf(name) != -1) {
                    String[] lineArray = line.split(" ");
                    logger.info(Arrays.toString(lineArray));
                    pid = lineArray[23].trim();
                    pidList.add(pid);
                }
            }
        } catch (IOException e) {
            logger.error("", e);
        }
        return pidList;
    }
    public static void killPid(java.util.List<String> pidsList){
        try {
            for (String s : pidsList) {
                Runtime.getRuntime().exec("taskkill /F /PID "+s);
            }
        } catch (IOException e1) {
            e1.printStackTrace();
        }
    }
    public static void main(String args[]) {
        WelcomeWindow welcomeWindow = new WelcomeWindow();
        welcomeWindow.showWelcomeWindow();
        //if (true)return;
        commonArgs = args;
        try {
            if (OSinfo.isWindows())
                UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsClassicLookAndFeel");
        } catch (Exception e) {
            e.printStackTrace();
        }
        TrayManager trayManager = new TrayManager();
        trayManager.init(new AbstractAction() {
            @Override
            public void actionPerformed(ActionEvent e) {
                if (TrayManager.CommandEnum.RUN.getCommand().equals(e.getActionCommand())) {
                    runServer(e);
                } else if (TrayManager.CommandEnum.STOPRUN.getCommand().equals(e.getActionCommand())) {
                    runServer(e);
                } else if (TrayManager.CommandEnum.REGISTER.getCommand().equals(e.getActionCommand())) {
                    //runRegister(e);
                } else if (TrayManager.CommandEnum.EXIT.getCommand().equals(e.getActionCommand())) {
                    mySpringApplication.stop();
                    killPid(getPID(APP));
                    System.exit(-1);
                } else if (TrayManager.CommandEnum.ABOUT.getCommand().equals(e.getActionCommand())) {
                    CInterface cInterface = mySpringApplication.getBean(CInterface.class);
                    System.out.println(cInterface.getStatus());
                } else if (TrayManager.CommandEnum.SETTING.getCommand().equals(e.getActionCommand())) {
                    SettingFrame settingFrame = new SettingFrame();
                    settingFrame.setVisible(true);
                    settingFrame.setMeeting(ConfigUtils.getMeeting());
                }
            }
        });
        ConfigUtils.checkNotAndCreate();
        mySpringApplication.run(commonArgs);
        welcomeWindow.exit();
        if (OSinfo.isWindows())
            startProgram(new File("app.exe").getAbsolutePath());
    }

    public static void startProgram(String programPath) {
        try {
            logger.warn(programPath);
            String programName = programPath.substring(programPath.lastIndexOf("/") + 1, programPath.lastIndexOf("."));
            java.util.List<String> list = new ArrayList<String>();
            list.add("cmd.exe");
            list.add("/c");
            list.add("start");
            list.add("\"" + programName + "\"");
            list.add("\"" + programPath + "\"");
            ProcessBuilder pBuilder = new ProcessBuilder(list);
            pBuilder.start();
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("应用程序：" + programPath + "不存在！");
        }
    }

    private static void runServer(ActionEvent e) {
        MenuItem menuItem = (MenuItem) e.getSource();
        if (TrayManager.CommandEnum.RUN.getCommand().equals(e.getActionCommand())) {
            menuItem.setLabel("启动中");
            menuItem.setEnabled(false);
            mySpringApplication.run(commonArgs);
            menuItem.setLabel("关闭服务");
            menuItem.setActionCommand(TrayManager.CommandEnum.STOPRUN.getCommand());
        } else if (TrayManager.CommandEnum.STOPRUN.getCommand().equals(e.getActionCommand())) {
            menuItem.setLabel("关闭中");
            menuItem.setEnabled(false);
            mySpringApplication.stop();
            menuItem.setActionCommand(TrayManager.CommandEnum.RUN.getCommand());
            menuItem.setLabel("启动服务");
        }
        menuItem.setEnabled(true);
    }
}
